//加载打印按钮
var WF_DocUnid = $("#WF_DocUnid").val(); //
var newWindow; 
var OpenWindow;
 function exportExcel(WF_DocUnid)  {//凭证接口
   window.open('r?wf_num=R_finance_B047&DocUnid='+$("#WF_DocUnid").val());
}  
function finprint(WF_DocUnid){
    var url = "https://192.168.13.170/birtreport/frameset?__report=expense_fin-expenses.rptdesign&docNo=" + $("#WF_DocUnid").val();
    window.open(url); 
}
function readProject(){//预览
    var readProject;
    if($("#WF_CurrentNodeid").val() == 'T10002' || $("#WF_CurrentNodeid").val()=='T10024'){
        readProject = $("#readProject").val();
    }else{
        readProject = $("#readProject").val();
        if(readProject === "" || readProject === undefined){
            readProject = $("span#readProject").text();
        }
    }
    if(readProject === ""){
        alert("请先查找立项申请单！");
        return;
    }else{
       var travelNoUrl = "rule?wf_num=R_S003_B062&wf_docunid=" + readProject;
        OpenUrl(travelNoUrl); 
    }
}
function readPR(){//预览
    var readPR;
    if($("#WF_CurrentNodeid").val() == 'T10002' || $("#WF_CurrentNodeid").val()=='T10024'){
        readPR = $("#readPR").val();
    }else{
        readPR = $("#readPR").val();
        if(readPR === "" || readPR === undefined){
           readPR = $("span#readPR").text();
        }
    }
    if(readPR === ""){
        alert("请先查找PO单！");
        return;
    }else{
       var travelNoUrl = "rule?wf_num=R_S003_B062&wf_docunid=" + readPR;
        OpenUrl(travelNoUrl); 
    }
}
function readGR(){//预览
    var readGR;
    if($("#WF_CurrentNodeid").val() == 'T10002' || $("#WF_CurrentNodeid").val()=='T10024'){
        readGR = $("#readGR").val();
    }else{
        readGR = $("#readGR").val();
        if(readGR === "" || readGR === undefined){
           readGR = $("span#readGR").text();
        }
    }
    if(readGR === ""){
        alert("请先查找会签单！");
        return;
    }else{
       var travelNoUrl = "rule?wf_num=R_S003_B062&wf_docunid=" + readGR;
        OpenUrl(travelNoUrl); 
    }
}

function readAdvance(){//预览
    var readAdvance;
    if($("#WF_CurrentNodeid").val() == 'T10002' || $("#WF_CurrentNodeid").val()=='T10024'){
        readAdvance = $("#readAdvance").val();
    }else{
        //readAdvance = $("span#readAdvance").text();
        jQuery.ajax({
    	  type:"post",
          async:false,
          url:"rule?wf_num=R_finance_B063&WF_DocUnid=" + $("#WF_DocUnid").val(),
          dataType:"text", 
          data:{},
          success:function(data){
                travelId = data.trim();
          }
    	});
    }
    if(readAdvance === ""){
        alert("请先查找预借预付款单！");
        return;
    }else{
       var travelNoUrl = "rule?wf_num=R_S003_B062&wf_docunid=" + readAdvance;
       OpenUrl(travelNoUrl); 
    }
}

function deleteProject(){
    $("#proCode").val("");
    $("#projectAmount").val("");
    $("#payVendorName").val("");
    $("#payUserName").val("");
    $("#userId").val("");
    $("#readProject").val("");
    $("#budgetNoProject").val("");
    $("#budgetProjectProject").val("");
    $("#payeeFull").val("");
    $("#bene_bank").val("");
    $("#bank_A_C").val("");
    $("#vendor_code").val("");
    $("#bene_bank").val("");
    $("#bank_A_C").val("");
    $("#vendor_code").val("");
}
function deletePR(){
    
    $("#proCodeofPR").val("");
    $("#prAmount").val("");
    $("#payVendorNameofPR").val("");
    $("#payUserNameofPR").val("");
    $("#userIdofPR").val("");
    $("#readPR").val("");
    $("#budgetNoPR").val("");
    $("#budgetProjectPR").val("");
    $("#ifLinkGR").combobox("setValue", '不关联会签单').combobox('disable');
	$('#findGR').hide();
	$("#payeeFull").val("");
    $("#bene_bank").val("");
    $("#bank_A_C").val("");
    $("#vendor_code").val("");
}
function deleteGR(){
    
    $("#proCodeofGR").val("");
    $("#grAmount").val("0");
    $("#readGR").val("");
}
function deleteAdvance(){
    
    $("#text12").val("0");
    $("#advanceCode").val("");
    $("#readAdvance").val("");
    $("#text12").removeAttr("readOnly","true");
    $("#text12").removeAttr('style','background-color: rgb(204, 204, 204);');
    
}
/*----------star----------*/
function selDocument(){
    spacialReimbTypeOfComCode("");
    var doctype = getDocType();
    $("#bene_bank").combobox('enable');
    $("#bank_A_C").combobox('enable');
    $("#ifLinkGR").combobox('enable');
    // $("#ifLinkGR").combobox('disable');
    if(isSupplierExp(doctype)){
        $('#bank_A_C').combobox('setValue',"").combobox('disable');
        $('#bene_bank').combobox('setValue',"").combobox('disable');
        $("#payeeFull").attr("readOnly","true");
        $("#payeeFull").attr('style','background-color: rgb(204, 204, 204);');
        deleteProject();
        deletePR();
    }
    
    if(isStaffExp(doctype)){
        deleteProject();
        deletePR();
        jQuery.ajax({
            type:"post",
            async:false,
            url:"rule?wf_num=R_finance_B023",
            dataType:"text",
            data:{
                userid:$("#staff_id").val(),
            },
            success:function(data){
                if (data) {
                    var _data = eval('(' + data + ')');
                    if (_data.length >0) {
                        $('#bank_A_C').combobox('setValue',_data[0].text);
                    }
                }
            }
        }); 
        jQuery.ajax({
            type:"post",
            async:false,
            url:"rule?wf_num=R_finance_B033",
            dataType:"text",
            data:{
                userid:$("#staff_id").val(),
            },
            success:function(data){
                if (data) {
                    var _data = eval('(' + data + ')');
                    if (_data.length >0) {
                        $('#bene_bank').combobox('setValue',_data[0].text);
                    }
                }
            }
        }); 
        $('#bank_A_C').removeAttr("readOnly","true");
        $('#bene_bank').removeAttr("readOnly","true");
        $("#payeeFull").removeAttr("readOnly","true");
        $("#payeeFull").removeAttr('style','background-color: rgb(204, 204, 204);'); 
    }
    
}
function isSupplierExp(doctype){
    if(doctype == '业务费用报销单-对公' || doctype == 'supplierExpenses'){
        return true; 
    }
    return false;
}

function isStaffExp(doctype){
    if(doctype == '业务费用报销单-员工' || doctype == 'staffExpenses'){
        return true; 
    }
    return false;
}

function getReimbTypeList(doctype){// 获取报销类型
    var _doctype = "";
    if(isStaffExp(doctype)){
       _doctype = "staffExpenses";
    }
    if(isSupplierExp(doctype)){
       _doctype = "supplierExpenses";
    }
    var uri="";
    if(_doctype !== ""){
        $("#reimbType").combobox({   
            url:"rule?wf_num=R_finance_B076&doctype=" + _doctype,
            valueField:'val', 
            textField:'text',
            onLoadSuccess:function() {
                var nowReimbType = $('#reimbType').val();
        	    var groupdata = $('#reimbType').combobox('getData');
        	    if (groupdata && groupdata.length>0) {
        	        for(var i=0; i<groupdata.length; i++){
        	            if(groupdata[i].val == nowReimbType){
        	                $('#reimbType').combobox("select",groupdata[i].val);
        	            }
        	        }
        	        
        	    } 
            }
        }); 
    }
    
}

function hideUpFile(meetingFile,deptPurchaseFile,donateFile,businessExpFile,leagueBuildingFile){
    var meetingStyle='none';
    var deptStyle='none';
    var donateStyle='none';
    var businessStyle='none';
    var leagueStyle='none';
    if(meetingFile){
        meetingStyle="";
    }
    if(deptPurchaseFile){
        deptStyle="";
    }
    if(donateFile){
        donateStyle="";
    }
    if(businessExpFile){
        businessStyle="";
    }
    if(leagueBuildingFile){
        leagueStyle="";
    }
    document.getElementById("meetingFile").style.display=meetingStyle;
    document.getElementById("meetingFile1").style.display=meetingStyle;
    document.getElementById("meetingFile2").style.display=meetingStyle;
    document.getElementById("meetingFile3").style.display=meetingStyle;
    document.getElementById("meetingFile4").style.display=meetingStyle;
    document.getElementById("deptPurchaseFile").style.display=deptStyle;
    document.getElementById("donateFile").style.display=donateStyle;
    document.getElementById("businessExpFile").style.display=businessStyle;
    document.getElementById("leagueBuildingFile").style.display=leagueStyle;
}

function _loadFile(newValue){
    hideUpFile('','','','','');
    if (newValue == "meeting" || newValue == "会议类") {// 会议类
        hideUpFile('meetingFile','','','','');
    } 
    if (newValue == "deptPurchase" || newValue == "部门采购") {//部门采购
        hideUpFile('','deptPurchaseFile','','','');
    } 
    if (newValue == "donate" || newValue == "捐赠") {// 捐赠
        hideUpFile('','','donateFile','','');
    } 
    if (newValue == "businessExp" || newValue == "业务招待费") {// 业务招待费
        hideUpFile('','','','businessExpFile','');
    } 
    if (newValue == "leagueBuilding" || newValue == "团建") {//团建
        hideUpFile('','','','','leagueBuildingFile');
    } 
}

function getDocType(){//获取单据类型
    var doctype = $("#doctype").html();
    if(doctype == ""){
        doctype = $("#doctype").combobox('getValue');
    }
    return doctype;
}

function onPayeeFullChange(){
    debugger
    var doctype = getDocType();
    if(isStaffExp(doctype)){
        $('#bank_A_C').combobox('setValue',"");
        $('#bene_bank').combobox('setValue',"");
    }
}


function buildBankInfo(){
    if(WF_DocUnid=='' || WF_DocUnid==undefined){
        WF_DocUnid=$("#WF_DocUnid").val();
    }
    jQuery.ajax({
        type:"post",
        async:false,
        url:"rule?wf_num=R_finance_B023",
        dataType:"text",
        data:{
            userid:$("#staff_id").val(),
            docID:WF_DocUnid,
            type:"fillAll"
        },
        success:function(data){
            if (data) {
                var _data = eval('(' + data + ')');
                if (_data.length >0) {
                    $('#bene_bank').combobox('setValue',_data[0].text);
                    $('#bank_A_C').combobox('setValue',_data[0].val);
                }
            }
        }
    }); 
}

function spacialReimbTypeOfComCode(type){
        var userid = $("#staff_id").val();//凭证
        var docID = $("#WF_DocUnid").val();
        var uri = "rule?wf_num=R_finance_B055&type=" + type + "&userid=" + userid +"&docUnid=" + docID;
        $("#comCode").combobox({   
            url:uri,
            valueField:'val', 
            textField:'text',
        });
}

/*----------end----------*/
var isSave=false;
function formonload(){
    var _reimbType=$("#reimbType").html();
    if(_reimbType==""){
        _reimbType = $("#reimbType").combobox('getValue');
    }
    _loadFile(_reimbType);
    //新建，只有新流程才可以编辑
    var newdoc = $("#WF_NewDocFlag").val();
    if(newdoc=="true" || $("#WF_IsFirstNodeFlag").val()=='true' || $("#WF_DocStatus").val()=='Draft'){
        hideUpFile("","","","","");
        $('#reimbType').combobox({
            onChange: function (newValue, oldValue) {
                var doctype = getDocType();
                if(isStaffExp(doctype)){
                    $("#payeeFull").removeAttr("readOnly","true");
                    $("#payeeFull").removeAttr('style','background-color: rgb(204, 204, 204);');
                }
                if(newValue=="businessExp" || newValue=="leagueBuilding" || newValue=="regionPromot" || newValue=="donate"){
                    deleteProject();
                    deletePR();
                }
                if(newValue=="adminRent"){
                    deleteProject();
                }
                if(newValue=="deptPurchase"){
                    deleteProject();
                    $("#ifLinkGR").combobox('enable');
                }else {
                    $("#ifLinkGR").combobox('disable');
                }
                var type="";
                if(newValue=="businessExp"){// 个人-业务招待费-收款人不能修改-姓名只能等于款人
                    $("#payeeFull").attr("readOnly","true");
                    $("#payeeFull").attr('style','background-color: rgb(204, 204, 204);');
                    $("#payeeFull").val($("#staff_name").val());
                    buildBankInfo();
                    type = "businessExp";
                }
                spacialReimbTypeOfComCode(type);
                _loadFile(newValue);
            }
        });
        $("#doctype").combobox({"editable":false});//combobox不能输入文本信息
        $("#cost_center").combobox({"editable":false});//combobox不能输入文本信息，也不能下拉选择
        $("#selVendor").show();
        if($("#WF_DocStatus").val()=='Draft'){
            buildBankInfo();
            var doctype = getDocType();
             $('#method_payment').combobox({"editable":false}).combobox({disabled:true});
            if(isSupplierExp(doctype)){
                $("#bene_bank").combobox('disable');
                $("#bank_A_C").combobox('disable');
                $("#findVendor").removeAttr('style','display: none;');
                $("#payeeFull").attr("readOnly","true");
                $("#payeeFull").attr('style','background-color: rgb(204, 204, 204);');
            }
            if(isStaffExp(doctype)){
                $("#findVendor").attr('style','display: none;');
                $("#bene_bank").combobox('enable');
                $("#bank_A_C").combobox('enable'); 
            }
        }
    }else{
        $("#selVendor").hide();
    }
    
    var isRead = $("#comCode")[0].tagName.toLocaleLowerCase();
    //span标签为只读状态，不加载事件
    if(isRead!="span"){
        //表单打开，加载combobox数据（For Copy启动的流程）
        var userid=$("#staff_id").val();//凭证
        initInfos(userid);
    }
    //接口财务审批环节显示凭证按钮id='WF_Processid' value='24a043ae0458d04ea80ab8d0e75c11ed4c46'凭证接口
    if(($("#WF_CurrentNodeid").val()=='T10024' || $("#WF_CurrentNodeid").val()=='T10009') && $("#WF_Processid").val()=='24a043ae0458d04ea80ab8d0e75c11ed4c46'){
        $('#checkproof').show();
    }else{
        $('#checkproof').hide();
    }
    var doctype = getDocType();
    if(isSupplierExp(doctype)){
        $("#title").text("业 务 费 用 报 销 单（对公）");
        $("#title1").text("Operating Expenses Reimbursement Form (Supplier)");
         //默认不可编辑，单据类型为对公预付款申请时才可编辑
        $("#vendor_code").attr('readonly',false);
        $("#vendor_code").attr('style','');
    }
    if(isStaffExp(doctype)){
        $("#title").text("业 务 费 用 报 销（员工）");
        $("#title1").text("Operating Expenses Reimbursement Form (Staff)");
        //默认不可编辑，单据类型为对公预付款申请时才可编辑
        $("#vendor_code").attr('readonly','readonly');
        $("#vendor_code").attr('style','background-color: rgb(204, 204, 204);');
    }
    
    //判断为驳回状态
    if((newdoc=="false" && $("#WF_IsFirstNodeFlag").val()=='true')||$("#WF_DocStatus").val()=='ARC'||$("#WF_DocStatus").val()=='Draft'){
        // $('input:radio[name=Reply]').each(function(index,domEle){//不知道干啥的，不敢删
        //     $(this).attr("disabled", "disabled"); 
        // });
        //驳回状态时合计等字段为不可编辑状态
        document.getElementById("text9").readOnly="readonly";
        //结束
        document.getElementById("text10").readOnly="readonly";
    }
    //默认不可编辑，单据类型为对公预付款申请时才可编辑
    $("#proCode").attr("readOnly","true");//关联单据默认不可编辑
    $("#projectAmount").attr("readOnly","true");
    $("#proCodeofPR").attr("readOnly","true");
    $("#prAmount").attr("readOnly","true");
    $("#proCodeofGR").attr("readOnly","true");
    $("#grAmount").attr("readOnly","true");
    $("#vendor_code").attr('readonly','readonly');
    $("#vendor_code").attr('style','background-color: rgb(204, 204, 204);');
}
//表单打开时按公司代码加载级联combobox
function initInfos(userid){
    //alert("表单打开时按公司代码加载级联combobox");
    $('#title').attr("disabled",false); 
    $('#title1').attr("disabled",false);
    var WF_DocUnid = $("#WF_DocUnid").val(); 
    var doctype = getDocType();
    if(isStaffExp(doctype)){
        //默认不可编辑，单据类型为对公预付款申请时才可编辑
        $("#vendor_code").attr('readonly','readonly');
        $("#vendor_code").attr('style','background-color: rgb(204, 204, 204);');
    }
    if(isSupplierExp(doctype)) {
         //默认不可编辑，单据类型为对公预付款申请时才可编辑
        $("#vendor_code").attr('readonly',false);
        $("#vendor_code").attr('style','');
    }
}

// 立项、PO、PC查找函数
function selVendor(type){
    //type :  project pr
    //staffExpenses 业务费用报销单-员工;supplierExpenses 业务费用报销单-对公
    var doctype = $("#doctype").combobox("getValue");
    if(doctype == null || doctype == ""){
        alert("请先选择单据类型！");
        return false;
    }
    var reimbType = $("#reimbType").combobox("getValue");
    if(reimbType === "leagueBuilding"){
        alert("团建不能关联立项单或PO/PC单！");
        return false;            
    }
    if(reimbType === "businessExp"){
        alert("业务招待费不能关联立项或PO/PC单！");
        return false;             
    }
    if(reimbType === "regionPromot" ){
        alert("区域推广不能关联立项或PO/PC单！");
        return false;             
    }
    if(reimbType === "donate" ){
        alert("捐赠不能关联立项或PO/PC单！");
        return false;             
    }
    if(reimbType === "deptPurchase" && type == "project"){
        alert("部门采购不能关联立项！");
        return false;             
    }
    if(reimbType === "adminRent" && type == "project"){
        alert("行政部房租类不能关联立项单！");
        return false;             
    }
    $('#win').window({
        width:800,
        height:500,
        top:320,
        modal:true,
        title:'查找关联单据'
    });
    if(type == "project"){// PO/PC单查找属兔
       $('#win').html("<iframe height='400px' width='100%' frameborder='0' src='r?wf_num=V_finance_G013&doctype="+doctype+"&type="+type+"'></iframe>"); 
    }else if(type == "po"){// 立项查找视图
        $('#win').html("<iframe height='400px' width='100%' frameborder='0' src='r?wf_num=V_finance_G015&doctype="+doctype+"&type="+type+"'></iframe>");
    }
}
function findVendor(){
    //advanceRequest 个人预借款申请;advancePayment 对公预付款申请
    var doctype = $("#doctype").combobox("getValue");
    if(doctype == null || doctype == ""){
        alert("请先选择单据类型！");
        return false;
    }
    var comCode = $("#comCode").combobox("getValue");
    if(comCode == null || comCode == ""){
        alert("请先选择所属公司！");
        return false;
    }
    
    $('#win').window({
        width:800,
        height:200,
        modal:true,
        title:'查找供应商'
    });
    $('#win').html("<iframe height='400px' width='100%' frameborder='0' src='r?wf_num=V_finance_G014&comCode="+comCode+"'></iframe>");
}
function selGR(){
    //advanceRequest 个人预借款申请;advancePayment 对公预付款申请
    var doctype = $("#doctype").combobox("getValue");
    if(doctype == null || doctype == ""){
        alert("请先选择单据类型！");
        return false;
    }
    var comCode = $("#comCode").combobox("getValue");
    if(comCode == null || comCode == ""){
        alert("请先选择所属公司！");
        return false;
    }
    var proCodeofPR = $("#proCodeofPR").val();
    if(proCodeofPR == null || proCodeofPR == ""){
        alert("请先选择所要关联的PR单！");
        return false;
    }
    $('#win').window({
        width:800,
        height:200,
        modal:true,
        title:'查找会签单'
    });
    $('#win').html("<iframe height='400px' width='100%' frameborder='0' src='r?wf_num=V_finance_G016&proCodeofPR="+proCodeofPR+"&comCode="+comCode+"&doctype="+doctype+"'></iframe>");
}
function selAdvance(){
    //staffExpenses 业务费用报销单-员工;supplierExpenses 业务费用报销单-对公
    var doctype = $("#doctype").combobox("getValue");
    if(doctype == null || doctype == ""){
        alert("请先选择单据类型！");
        return false;
    }
    var comCode = $("#comCode").combobox("getValue");
    if(comCode == null || comCode == ""){
        alert("请先选择所属公司！");
        return false;
    }
    var proCode = $("#proCode").val();//立项单单号
    var proCodeofPR = $("#proCodeofPR").val();//PR单单号
    var payeeFull = $("#payeeFull").val();//收款人/供应商
    
    $('#win').window({
        width:800,
        height:200,
        modal:true,
        title:'查找预借预付款单'
    });
    
    $('#win').html("<iframe height='400px' width='100%' frameborder='0' src='r?wf_num=V_finance_G017&proCodeofPR="+proCodeofPR+"&comCode="+comCode+"&proCode="+proCode+"&payeeFull="+payeeFull+"&doctype="+doctype+"'></iframe>");
}

function isEmpty(val){
    if(val=='' || val == null || val ==undefined || val=='undefined'){
        return true;
    }
    return false;
}
var flag = "";
// 子表单验证逻辑
function verifSubFrom(doctype,flag){
    var vals = ['日期','摘要','币种','发票类型','人民币金额','税额','是否预算内','归属人','费用类型','附件编号','预提号'];
	var rows = $("#dg").datagrid('getRows');
  	if(!(rows && rows.length > 0)){
        alert("表体不能为空！");
        return false;
    }
    var rows = $("#dg").datagrid('getRows');
    for(var i = 0; i < rows.length; i++){
        var row = rows[i];
        var str="";
        // var _keys = [row.date_fill, row.budget_dept, row.expenses_item,  row.currency, row.FC_Amount, row.belongEmp,row.bNum];
        var _keys = [row.date_fill, row.description, row.currency,  row.if_tax, row.Amount, row.tax_amount, row.is_budget, row.belongEmp, row.expenses_item, row.invoices, row.bNum];
        for(var j = 0; j < _keys.length; j++){
            if(isEmpty(_keys[j])){
                str +=  vals[j]+"、";
            }
        }
        if(row.if_tax === "增值税专用发票" && isEmpty(row.invoice_number)){
            str +=  "增值税专用发票的发票号、";   
        }
        if(str.length > 0){
            alert("第" + (i+1) + "行：" + str + "不能为空！");
            return false;
        }
        
    }
    return true;
}

// 子表单验证逻辑
function inDepthVerifSubFrom(){
    debugger
    var reimbType = $("#reimbType").combobox('getValue');
    var doctype = $("#doctype").combobox('getValue');
    var costCenterCode = $("#cost_center").combobox('getValue');
    var rows = $("#dg").datagrid('getRows');
    var dataList = new Array();
    for(var i = 0; i < rows.length; i++){
        var obj = new Object();
        obj.expensesItem =rows[i].expenses_item;
        obj.budgetDept =rows[i].budget_dept;
        dataList.push(obj);     
    }
    var result = {status:'success',msg:'success'};
    jQuery.ajax({
        type:"post",
        async:false,
        url:"rule?wf_num=R_finance_B083",
        dataType:"text",
        data:{
            dataList:JSON.stringify(dataList),
            reimbType:reimbType,
            doctype:doctype,
            costCenterCode:costCenterCode
        },
        success:function(data){
            if(data){
                result = eval("("+data+")");
            }
        }
    });
    return result;
}

var isDocError = false;
function verifDoc(){
    if(isDocError){
        alert("文档保存错误,请核对数据是否正确！");
        return false;
    }
    return true;
}

// 验证立项单均摊金额是否超出
function verifTotalAmount(processID,doctype,docID,proCode,totalAmount,projectAmount){
    var result = {"status":1,"code":"fail","msg":"立项类均摊金额验证失败！"}
    jQuery.ajax({
        type:"post",
        async:false,
        url:"rule?wf_num=R_finance_B079",
        dataType:"text",
        data:{
            processID:processID,
            docID:docID,
            proCode:proCode,
            totalAmount:totalAmount,
            projectAmount:projectAmount,
            doctype:doctype
        },
        success:function(data){
            if(data){
                result = eval("("+data+")");
            }
        }
    }); 
    return result;
}

function formonsubmit(){
    debugger
    // 是否表单填写节点
    if($("#WF_IsFirstNodeFlag").val()!='false' || $('#WF_CurrentNodeid').val()=='T10024') {
        var doctype = $("#doctype").combobox('getValue');
        //计算合计金额
        computer0();
        // 子表单验证逻辑
        if(!verifSubFrom(doctype,flag)){
            return false;
        }
        var res = inDepthVerifSubFrom();
        if(res && res.status=="fail"){
            alert("第" + res.msg + "行费用类型不合法！");
            return false;
        }
        //保存明细信息
        saveDetail();
        //Excel验证
        if(!verifDoc()){
            return false;
        }
        /** 特殊类型验证  star **/
        // 会议类关联立项单验证
        var reimbType = $("#reimbType").combobox('getValue');
        var proCode = $("#proCode").val();
        if(reimbType == "meeting" || reimbType == "会议类"){
            if(proCode == "" || proCode == null){
                $.messager.alert('提示', '会议类费用申请，必须关联立项申请单！', 'info');
        	    return false;
            }
        }
        // 部门采购类型必须关联PO/PC单
        var proCodeofPR = $("#proCodeofPR").val();//PR编号
        var proCodeofGR = $("#proCodeofGR").val();
        if(reimbType == "deptPurchase" || reimbType == "部门采购"){
            if(proCodeofPR == "" || proCodeofPR == null){
                // alert("部门采购类型申请，必须关联PO/PC单！");
                $.messager.alert('提示', '部门采购类型申请，必须关联PO/PC单！', 'info');
        	    return false;
            }
            if(proCodeofGR == "" || proCodeofGR == null){
                $.messager.alert('提示', '部门采购类型申请，必须关联会签单！', 'info');
        	    return false;
            }
        }
        // 供应商编码验证
        var vendor_code = $("#vendor_code").val();
        if(doctype == "supplierExpenses" && vendor_code == ""){//业务费用报销单-对公
            $.messager.alert('提示','业务费用报销单-对公，请填写供应商编码！', 'info');
        	return false;
        }
        // 会签单验证
        var ifLinkGR = $("#ifLinkGR").combobox('getValue');
        if((ifLinkGR == "linkGR" || ifLinkGR == "关联会签单") && proCodeofGR == ""){
            $.messager.alert('提示','已选择关联会签单时，必须选择关联的会签单！', 'info');
        	return false;
        }
        $("#bene_bank").removeAttr("disabled"); 
        $("#bank_A_C").removeAttr("disabled");
        // 开户行和银行卡号验证
        var bankAC = document.getElementById("bank_A_C").innerHTML;
        var beneBank = document.getElementById("bene_bank").innerHTML;
        if(bankAC == "null" || bankAC == null || bankAC == ""){
           bankAC = $("#bank_A_C").combobox("getValue");
        }
        if(beneBank == "null" || beneBank == null || beneBank == ""){
           beneBank = $("#bene_bank").combobox("getValue");
        }
        if((bankAC == "null" || bankAC == null || bankAC == "")||((beneBank == "null" || beneBank == null || beneBank == ""))){
            $.messager.alert('提示','银行卡或账号不能为空！', 'info');
            return false;
        }
        /** 特殊类型验证  end **/
        
        // 金额验证是否合法
        var processID = $("#WF_Processid").val();//流程ID
        var text9 = $("#text9").val();//合计金额
        var projectAmount = $("#projectAmount").val();//立项金额 proCode 立项编号
        
        var prAmount = $("#prAmount").val();//PR金额
        var grAmount = $("#grAmount").val();//GR金额 proCodeofGR GR编号
        if(proCode != ""){
            if(parseFloat(text9) > parseFloat(projectAmount)){
               $.messager.alert('提示', '申请金额不能大于立项单金额，请修改！', 'info');
                return false;
            }
            var __docID = $("#WF_DocUnid").val();
            // 验证立项单均摊金额是否超出
            var result = verifTotalAmount(processID,doctype,__docID,proCode,text9,projectAmount);
            if(result.code == 'fail' || result.status == 1){
                $.messager.alert('提示', result.msg, 'info');
        	    return false;
            }
        }
        if(proCodeofPR != "" && (parseFloat(text9) > parseFloat(prAmount))){
            $.messager.alert('提示', '申请金额不能大于PO/PC单金额，请修改！', 'info');
            return false;
        }
        if(proCodeofGR != "" && (parseFloat(text9) > parseFloat(grAmount))){
             $.messager.alert('提示','申请金额不能大于会签单金额，请修改！', 'info');
            return false;
        }
        
        /** 基础数据  star **/
        //修改流程名称
      	if ($("#Subject").val()=='' || $("#Subject").val()=='业务费用报销') {
            $("#Subject").val($("#staff_name").val()+$("#appl_date").datebox('getValue')+$("#WF_ProcessName").val());
        }
        /** 基础数据  end **/
        
        if(!confirm("请再次确认开户行和银行账号是否正确！")){
            return false;
        }
    }
}
//暂存办理
function GoToSaveDoc(){
    flag="2";
    computer0();
	$("#WF_Remark").val($("#WF_TmpRemark").val());
	var formData=$("form").serialize();
	var checkBoxData=getNoCheckedBoxValue();
	if(checkBoxData!=""){formData+="&"+checkBoxData;}
	var textShowStr=getFieldTextShowData();
	if(textShowStr!=""){formData+="&"+textShowStr;} //_show字段的内容
	var r=formonsubmit();
	//alert("===="+typeof(r));
	if(typeof(r)=="boolean" && r==false){return;}
	else if(typeof(r) == "string"){formData+="&"+r;} //如果返回的时字符串则作为提交的附加数据
	var url="r?wf_num=R_S003_B031";
	if(!confirm("您确认要暂存文档吗?")){return false;}
	mask();
	$.post(url,formData,function(data){unmask();});
    window.parent.$('#tree').tree('reload');
}
//办理完成
// function GoToNextNode(){ 
//     flag="1";
// 	//提交到下一环节
// 	var NodeList=""; //获得选中的节点
// 	$('input[name="WF_NextNodeSelect"]:checked').each(function(){
// 		if(NodeList==""){NodeList=$(this).val();}
// 		else{NodeList+=","+$(this).val();}
// 	});
// 	if($('input[name="WF_NextNodeSelect"]').length>0){ //看是否可以选择环节
// 		if(NodeList==""){alert("请选择一个环节再提交!");return false;}
// 		//获得审批用户列表
// 		var UserList="";
// 		var NodeArray=NodeList.split(",");
// 		for(var i=0;i<NodeArray.length;i++){
// 			var Nodeid=NodeArray[i];
// 			var obj=$("#WF_"+Nodeid);
// 			if(obj.length>0){
// 				var NodeName=obj.attr("NodeName");
// 				var MaxUserNum=obj.attr("MaxUserNum")-0;
// 				var MinUserNum=obj.attr("MinUserNum")-0;
// 				var userList=obj.val()+"";
// 				var UserArray=userList.split(",");
// 				if(UserArray.length>MaxUserNum && MaxUserNum!=0){alert("环节("+NodeName+")超出最大可选参与人数!");return false;}
// 				if((userList=="null" || userList=="") && MinUserNum!=0){
// 					alert("环节("+NodeName+")没有指定任务处理人!");
// 					return false;
// 				}
// 				if(UserArray.length<MinUserNum){alert("环节("+NodeName+")少于最小参与人数!"); return false;}
// 				for(var j=0;j<UserArray.length;j++){
// 					if(UserArray[j]!=""){
// 						if(UserList==""){UserList=UserArray[j]+"$"+Nodeid;}else{UserList+=","+UserArray[j]+"$"+Nodeid;}
// 					}
// 				}
// 			}
// 		}
// 		$("#WF_NextNodeid").val(NodeList);
// 		$("#WF_NextUserList").val(UserList);
// 	}
// 	SaveDocument("EndUserTask","您确认要提交本流程吗?");
// }
//凭证接口
//WF_Action为引擎动作id,WF_Params为post时的附加参数,msg为提示消息
// function SaveDocument(WF_Action,msg,WF_Params){
// 	if(WF_Action==undefined || WF_Action==""){WF_Action="EndUserTask";}
//  	if(GetRemarkStr()==false){return;}
// 	var formData="";
// 	var checkBoxData=getNoCheckedBoxValue();
// 	if(checkBoxData!=""){formData=checkBoxData;} //单选复选框提交
// 	var textShowStr=getFieldTextShowData();
// 	if(textShowStr!=""){formData+="&"+textShowStr;} //_show字段的内容
// 	if(WF_Action){formData+="&WF_Action="+WF_Action;} //要提交的动作，默认为EndUserTask办理完成
// 	formData+="&WF_CopyUserList="+encodeURIComponent($("#WF_SelCopyUser").val()); //要抄送的用户列表
// 	if($("#WF_SelSendSms").val()!=undefined){
// 		formData+="&WF_SendSms="+$("#WF_SelSendSms").val();  //1表示手机短信发送标记
// 	}
// 	if(WF_Params!=undefined && WF_Params!=""){
// 		formData+="&"+WF_Params; //传入的附加post参数,传入的WF_Params要进行utf-8编码
// 	}
// 	//alert("开始表单验证");
// 	//开始表单验证
// 	var isValid = $("#linkeyform").form('validate');
// 	if (isValid){
// 		var r=formonsubmit();
// 		if(typeof(r)=="boolean" && r==false){return;}
// 		else if(typeof(r) == "string"){formData+="&"+r;} //如果返回的时字符串则作为提交的附加数据
// 		r=validReadFieldIsNull();
// 		if(r==false){return false;} //检测只读的字段是否有必填选项
//  	}else{
// 		alert("表单验证未通过,请检查表单数据后再次提交!");return;
//  	}
// 	//序列号表单字段
// 	formData+="&"+$("#linkeyform").serialize();
// 	//显示提示消息
// 	if(msg!="" && msg!=undefined){if(!confirm(msg)){return false;}}
// 	//凭证接口
// 	mask();
// 	var url="r?wf_num=R_S003_B035";
// 	$.post(url,formData,function(data){
// 		unmask();
// 		var rs = eval('(' + data + ')');
// 		if(isMobile()){alert(rs.msg);location.replace("r?wf_num=P_S023_004");
// 		}else{
// 		    //alert("进入回调函数中。。。");
// 		    SaveDocumentCallBack(WF_Action,rs);
		    
// 		}
//   	});
// }
//保存预借(预付)款申请单的子表数据
function saveDetail(){
	GetEditorValList();
	//保存编辑表格明细
    var WF_DocUnid = $("#WF_DocUnid").val(); 
    var EditorValList = $("#EditorValList").val().replaceAll("'","").replaceAll("&"," ");
    jQuery.ajax({
        type:"post",
        async:false,
        url:"rule?wf_num=R_finance_B052&DocUnid=" + WF_DocUnid,
        dataType:"text",
        data:{
            doctype:$('#doctype').combobox('getValue'),
            EditorValList:EditorValList 
        },//Excel验证   
        success:function(data){
            var d = eval("("+data+")");
            if(d.success){
                isDocError = false;
            }else{
                isDocError = true;
            }
        }
    }); 
    
    //保存对应单据信息
    var DocUnid = $("#WF_DocUnid").val();
    var text9 = $("#text9").val();//表头合计金额
	var proCode = $("#proCode").val();//立项单单号 
	var projectAmount = $("#projectAmount").val();//立项单金额 
	var proCodeofPR = $("#proCodeofPR").val();//PO单单号
	var prAmount = $("#prAmount").val();//PO单金额
	var proCodeofGR = $("#proCodeofGR").val();//会签单单号
	var grAmount = $("#grAmount").val();//会签单金额
	var canUseAmount = $("#canUseAmount").val();//PO单可用金额
	jQuery.ajax({
        type:"post",
        async:false,
        url:"rule?wf_num=R_finance_B071",
        dataType:"text",
        data:{
            DocUnid:DocUnid,
            text9:text9,
            proCode:proCode,
            projectAmount:projectAmount,
            proCodeofPR:proCodeofPR,
            prAmount:prAmount,
            proCodeofGR:proCodeofGR,
            grAmount:grAmount,
            canUseAmount:canUseAmount
        },//Excel验证   
        success:function(data){
            var d = eval("("+data+")");
            if(d.success){
                isDocError = false;
            }else{
                isDocError = true;
            }
        }
    }); 
    
}
//新增加获取报销单中详细编辑表格
function GetEditorValList(){
    // stopEditRow1();
    var rows = $("#dg").datagrid('getRows');
	var val = "";
	var v = "";
	var valList = "";
	//var fdList = "date_fill,description,currency,FC_Amount,FX_rate,if_tax,Amount,tax_amount,is_budget,budget_dept,expenses_item,budget_item,budget_no,attachmentRemark,invoices"; //编辑表格所有可编辑字段
	//date_fill 日期,description 摘要,currency 币种,FC_Amount 外币金额,FX_rate 汇率,if_tax 发票类型,Amount 人民币金额,tax_amount 税额,is_budget 预算内,budget_dept 预算部门,subBudget_dept 子部门,
	//expenses_item 费用类型,budget_item 预算项目,budget_no 预算号,budget_name 预算名称,attachmentRemark 附件说明,invoices 附件编号,belongEmp 归属人
	var fdList = "date_fill,description,currency,FC_Amount,FX_rate,if_tax,Amount,tax_amount,is_budget,budget_dept,subBudget_dept,expenses_item,budget_item,budget_no,budget_name,attachmentRemark,invoices,belongEmp,bNum,invoice_number"; 
	//编辑表格所有可编辑字段
	var fdArray = fdList.split(","); //分隔数组分别取值
	$.each(rows, function (i, row) {
	    val = "";
	    for(j=0;j<fdArray.length;j++){
	        v = eval("row."+fdArray[j]);
	        val = val +"<"+fdArray[j]+">"+v+"</"+fdArray[j]+">";
	    }
		//累加编辑表格值
		valList = valList+"<attrbute>"+val+"</attrbute>";
	});
	var xmlValList = "<editinfo>"+valList+"</editinfo>";
	$("#EditorValList").val(xmlValList);
}
function stopEditRow1(){
	$('#dc').datagrid('endEdit', editFlag);
	editFlag = undefined;
}

//计算明细合计金额，判断是否预算内，判断是否有会议费
function computer0(){
    //alert("计算明细合计金额，判断是否预算内，判断是否有会议费");
    var rows = $("#dg").datagrid('getRows'); 
    //var tet = parseFloat(0.00);//人民币金额
    var amount=parseFloat(0.00);
    var taxSum = parseFloat(0.00);//可抵扣增值税金额合计
    var taxSumNo = parseFloat(0.00);//可抵扣非增值税金额合计
    $("#budget").val("Y");//默认是预算内
    $("#expenses").val("N");//默认没有会议费
    var sumAir = parseFloat(0.00);//
    var sumCar = parseFloat(0.00);//
    var sumTrain = parseFloat(0.00);//
    var sumEle = parseFloat(0.00);//
    var taxSumAir = parseFloat(0.00);//
    var taxSumCar = parseFloat(0.00);//
    var taxSumTrain = parseFloat(0.00);//
    var taxSumEle = parseFloat(0.00);//
    
	stopEditRow();

    if(rows.length <= 0){
        alert("请新增明细信息！");
        return false;
    }
    var totalTaxAmount = parseFloat(0.00);//可抵扣增值税金额（new）
    for(var i = 0;i < rows.length;i++){
        var row = rows[i]
        var dgAmount = row.Amount;//人民币金额（不含税）
        var tax_amount = row.tax_amount;//税额
        //1）手填： 增值税专用发票、增值税电子普通发票(交通类)、增值税普通发票(其他)
        //2）系统带出：飞机票(可抵扣)、飞机票(不可抵扣)、火车票(实名)、汽车票+船票(实名)、其他发票(非实名)系统自动核算税额。
        //税额结算方式：飞机票(可抵扣)、火车票(实名)=本位币金额/1.09*0.09；汽车票+船票(实名)=本位币金额/1.03*0.03；
        //飞机票(不可抵扣)、其他发票(非实名)=0
        //可抵扣增值税金额: 增值税专用发票、增值税电子普通发票(交通类) 的税额合计
        //可抵扣非增值税金额:增值税普通发票(其他)、飞机票(可抵扣)、火车票(实名)、汽车票+船票(实名) 的税额合计
        //合计数=《增值税专用发票、增值税电子普通发票(交通类)、增值税普通发票(其他)  人民币金额+税额》
        //+《飞机票(可抵扣)、飞机票(不可抵扣)、火车票(实名)、汽车票+船票(实名)、其他发票(非实名) 中人民币金额》
        //交通费可抵扣税额=飞机票(可抵扣) 的税额 + 火车票(实名) 的税额 + 汽车票+船票(实名) 的税额
        var typeArr = ["增值税专用发票","飞机票(可抵扣)"];
        var typeArr0 = ["增值税专用发票","增值税电子普通发票(交通类)","增值税电子普通发票(非交通类)","增值税普通发票(其他)"];
        var typeArr1 = ["增值税专用发票","增值税电子普通发票(交通类)","增值税电子普通发票(非交通类)"];
        var typeArr2 = ["增值税普通发票(其他)","飞机票(可抵扣)","火车票(实名)","汽车票+船票(实名)"];
        var typeArr3 = ["飞机票(不可抵扣)","其他发票(非实名)"];
        var if_Tax = row.if_tax;//发票类型
        if(!typeArr0.includes(if_Tax)){// 税额不统计
            tax_amount = 0;
        }
        if(typeArr.includes(if_Tax)){// 税额统计
            totalTaxAmount += parseFloat(row.tax_amount);
        }
        if(typeArr1.includes(if_Tax)){// 是否包含
            taxSum += parseFloat(tax_amount);
            amount+=parseFloat(dgAmount);
            if(if_Tax == typeArr1[1]){
                taxSumEle += parseFloat(tax_amount)
                sumEle += parseFloat(dgAmount) - parseFloat(tax_amount);
            }
        }else if(typeArr2.includes(if_Tax)){
            if(if_Tax != typeArr2[0]){
               taxSumNo += parseFloat(tax_amount); 
            }else{
                amount+=parseFloat(tax_amount);
            }
            amount+=parseFloat(dgAmount);
            //Tax_Amount+=parseFloat(rows[i].tax_amount)//计算税额的求和营改增
            if(if_Tax == typeArr2[1]){
              taxSumAir += parseFloat(tax_amount);
              sumAir += parseFloat(dgAmount) - parseFloat(tax_amount);
            }
            if(if_Tax == typeArr2[2]){
              taxSumTrain += parseFloat(row.tax_amount)
              sumTrain += parseFloat(dgAmount) - parseFloat(tax_amount);
            }
            if(if_Tax == typeArr2[3]){
              taxSumCar += parseFloat(row.tax_amount)
              sumCar += parseFloat(dgAmount) - parseFloat(tax_amount);
            }
        }else if(typeArr3.includes(if_Tax)){
            amount+=parseFloat(dgAmount);
        }else{
            amount+=parseFloat(dgAmount);
            tax_amount+=parseFloat(tax_amount);//营改增
            // Tax_Amount+=parseFloat(rows[i].tax_amount);//计算税额的求和营改增
        }
        
        var rowsBudget = row.is_budget;
        var rowsExpenses = row.expenses_item;
        if(rowsBudget == "N"){
            $("#budget").val(rowsBudget);
        }
    }
    $("#text9").val((amount + taxSum + taxSumNo).toFixed(2));
    $("#text10").val(DX((amount + taxSum + taxSumNo).toFixed(2)));
    var text9 = $("#text9").val();
    var littleAmount = text9 - $("#text12").val();
    var littleAmount1 = $("#text12").val() - text9;
    if(littleAmount < 0){
        $("#text13").val('0'); 
        $("#text17").val('零');
        //应退回公司text14
        $("#text14").val(littleAmount1.toFixed(2)); 
        $("#text18").val(DX(littleAmount1.toFixed(2))); 
    }else{
        $("#text13").val(littleAmount.toFixed(2));
        $("#text17").val(DX( $("#text13").val()));
        $("#text14").val('0'); 
        $("#text18").val('零'); 
    }
    var text12 = $("#text12").val();
    if(text12 == '0'){
        $("#text16").val('零');  
    }else{
        $("#text16").val(DX(text12));
    } 
    // $("#added_amount_tax").val(taxSum.toFixed(2));//可抵扣增值税金额
    $("#added_amount_tax").val(totalTaxAmount.toFixed(2));//可抵扣增值税金额
    $("#added_noamount_tax").val(taxSumNo.toFixed(2));//可抵扣非增值税金额
   	//$("#added_travelamount_tax").val(added_travelamount_tax.toFixed(2));//交通费税额
   	$("#added_airamount").val(sumAir.toFixed(2));//
   	$("#added_caramount").val(sumCar.toFixed(2));//
   	$("#added_trainamount").val(sumTrain.toFixed(2));//
   	$("#added_eleamount").val(sumEle.toFixed(2));//
   	
   	$("#added_airamount_tax").val(taxSumAir.toFixed(2));//
   	$("#added_caramount_tax").val(taxSumCar.toFixed(2));//
   	$("#added_trainamount_tax").val(taxSumTrain.toFixed(2));//
   	$("#added_eleamount_tax").val(taxSumEle.toFixed(2));//

}
//数字转大写
function DX(n) {
        if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))
            return "数据非法";
        var unit = "千百拾亿千百拾万千百拾元角分", str = "";
            n += "00";
        var p = n.indexOf('.');
        if (p >= 0)
            n = n.substring(0, p) + n.substr(p+1, 2);
            unit = unit.substr(unit.length - n.length);
        for (var i=0; i < n.length; i++)
            str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
        return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整");
}
function SaveDocumentCallBack(btnAction,rs){
	//保存成功后的回调函数
  	//凭证接口
  	//alert("保存成功后的回调函数");
  	//var WF_CurrentNodeid=$('#WF_CurrentNodeid').val();
  	var WF_DocUnid = $("#WF_DocUnid").val();
    var createTime = "";
    
    jQuery.ajax({
        type: "post",
        async: false,          
        url: "rule?wf_num=R_finance_B049",
        dataType: "text",
        data:{
            WF_DocUnid: WF_DocUnid
        },
        success: function (data) {
            //createTime = data.msg;
            createTime = data;
            //alert("createTime=====" + createTime);
        }
    });
    alert(rs.msg); //提交成功后增加提醒
    location.href="view?wf_num=V_S005_G001";
    try{
      opener.$('#dg').datagrid('reload');
    }catch(e){}
    
    //window.close();
    if(confirm("是否继续填写新的业务费用报销单？")){
        //window.location.href = "https://192.168.13.191/bpm/login";
        window.location.href = "rule?wf_num=R_S003_B036&wf_processid=4d289f2106a70042670836b046312aaea69f";
    }else{
        window.close();
    }
    
}
//凭证接口
function addScriptTag(src) {
  var script = document.createElement('script');
  script.setAttribute("type","text/javascript");
  script.src = src;
  //alert("凭证接口页面script====" + script);
  document.body.appendChild(script);
}
function getNewMsg(msg){
    var url = "rule?wf_num=R_MDM_P033&msg="+encodeURIComponent(msg);
    var rs = "";
    jQuery.ajax({
        type: "post",
        async: false,          
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            rs = data.msg;
        }
    });
    return rs;
}
//根据公司查询预算部门()
function initfirstCombox(rowIndex){
    var typeArr = ["飞机票(可抵扣)","飞机票(不可抵扣)","火车票(实名)","汽车票+船票(实名)","其他发票(非实名)"];
    var comCode = $('#comCode').combobox('getValue');
    var doctype = $('#doctype').combobox('getValue');
    var reimbType = $("#reimbType").combobox("getValue");
    var userid = $("#staff_id").val();//凭证
    // var row = $('#dg').datagrid('getSelected',rowIndex);
	var target = $('#dg').datagrid('getEditor', {index:rowIndex,'field':'budget_dept'}).target;
	var row = $("#dg").datagrid('getRows')[rowIndex];
    var budget_dept = row.budget_dept;
    var expenses_item = row.expenses_item;
    var budget_item = row.budget_item;
    var attachmentRemark = row.attachmentRemark;
    var belongEmp = row.belongEmp;
    var tax = row.if_tax;
    //选择发票类型
    var taxTarget = $('#dg').datagrid('getEditor', {index:rowIndex,'field':'if_tax'}).target;
    var taxUrl = 'rule?wf_num=R_finance_B048';
    taxTarget.combobox({ 
        url:taxUrl,
    	valueField:'id',
    	textField:'text',
    	onLoadSuccess : function() {
	        var  taxValue = taxTarget.combobox('getData');
	        if(taxValue.length > 0){
	           for (var i = 0; i < taxValue.length; i++) { 
                    if (taxValue[i].id == tax) {
                        taxTarget.combobox('select', tax); //循环判断，如果某项一致，则该项选中  
                    }  
                }  
	        }else{
	            taxTarget.combobox('select', tax);  //
	        }
    	},
    	onSelect:function(rec) {
    	    var taxTargetValue = taxTarget.combobox('getValue');
    	    var taxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'tax_amount'}).target;
    	    var amountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'Amount'}).target;
    	    var amount = parseFloat(amountTarget.val());
    	   // var noTaxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'noTaxAmount'}).target;
    	    //1）手填： 增值税专用发票、增值税电子普通发票(交通类)
            //2）系统带出：增值税普通发票(其他)、飞机票(可抵扣)、飞机票(不可抵扣)、火车票、汽车票+船票(实名)、其他发票(非实名)系统自动核算税额。
            //税额结算方式：飞机票(可抵扣)、火车票=本位币金额/1.09*0.09；汽车票+船票(实名)=本位币金额/1.03*0.03；
            //增值税普通发票(其他)、飞机票(不可抵扣)、其他发票(非实名)=0
            taxAmountTarget.val(0.00);
            if(typeArr.includes(taxTargetValue)){// 禁止填写税额集合
                if(taxTargetValue == "飞机票(可抵扣)"){
        	        var taxAmountValue = (amount / 1.09 * 0.09).toFixed(2);
        	        taxAmountTarget.val(taxAmountValue);
        	    }
        	    $(taxAmountTarget).attr("disabled", true);
    	        taxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
            }else{
    	        $(taxAmountTarget).attr("disabled", false);
    	        taxAmountTarget.prop('style','background-color: rgb(255, 255, 255);');
    	    }
    	   // if(taxTargetValue == "飞机票(可抵扣)"){
    	   //     var taxAmountValue = (amount / 1.09 * 0.09).toFixed(2);
    	   //     taxAmountTarget.val(taxAmountValue);
    	   //     $(taxAmountTarget).attr("disabled", true);
    	   //     taxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	   // }else{
    	   //     $(taxAmountTarget).attr("disabled", false);
    	   //     taxAmountTarget.prop('style','background-color: rgb(255, 255, 255);');
    	   // }
    	    
    	}
    }).combobox({"editable":false});
    //填写本位币金额
    var amountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'Amount'}).target;
    
    amountTarget.numberbox({ 
    	onChange:function(newValue,oldValue) {
    	    var taxTargetValue = taxTarget.combobox('getValue');
    	    var taxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'tax_amount'}).target;
    	    //1）手填： 增值税专用发票、增值税电子普通发票(交通类)
            //2）系统带出：增值税普通发票(其他)、飞机票(可抵扣)、飞机票(不可抵扣)、火车票、汽车票+船票(实名)、其他发票(非实名)系统自动核算税额。
            //税额结算方式：飞机票(可抵扣)、火车票=本位币金额/1.09*0.09；汽车票+船票(实名)=本位币金额/1.03*0.03；
            //增值税普通发票(其他)、飞机票(不可抵扣)、其他发票(非实名)=0
            taxAmountTarget.val(0.00);
            if(typeArr.includes(taxTargetValue)){// 禁止填写税额集合
                if(taxTargetValue == "飞机票(可抵扣)"){
        	        var taxAmountValue = (parseFloat(newValue) / 1.09 * 0.09).toFixed(2);
        	        taxAmountTarget.val(taxAmountValue);
        	    }
        	    $(taxAmountTarget).attr("disabled", true);
    	        taxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
            }else{
    	        $(taxAmountTarget).attr("disabled", false);
    	        taxAmountTarget.prop('style','background-color: rgb(255, 255, 255);');
    	    }
    	   // if(taxTargetValue == "飞机票(可抵扣)"){
        //         var taxAmountValue = (parseFloat(newValue) / 1.09 * 0.09).toFixed(2);
    	   //     taxAmountTarget.val(taxAmountValue);
    	   //     $(taxAmountTarget).attr("disabled", true);
    	   //     taxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	   // }else{
    	   //     $(taxAmountTarget).attr("disabled", false);
    	   //     taxAmountTarget.prop('style','background-color: rgb(255, 255, 255);');
    	   // }
    	}
    });
    //////////////////////
    //numberbox事件触发
    //填写税额
    var taxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'tax_amount'}).target;
    
    taxAmountTarget.numberbox({ 
    	onChange:function(newValue,oldValue) {

    	    var taxTargetValue = taxTarget.combobox('getValue');
    	    var amountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'Amount'}).target;
    	    var amount = parseFloat(amountTarget.val());
    	    
    	   // var noTaxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'noTaxAmount'}).target;
    	    //1）手填： 增值税专用发票、增值税电子普通发票(交通类)
            //2）系统带出：增值税普通发票(其他)、飞机票(可抵扣)、飞机票(不可抵扣)、火车票、汽车票+船票(实名)、其他发票(非实名)系统自动核算税额。
            //税额结算方式：飞机票(可抵扣)、火车票=本位币金额/1.09*0.09；汽车票+船票(实名)=本位币金额/1.03*0.03；
            //增值税普通发票(其他)、飞机票(不可抵扣)、其他发票(非实名)=0
    	    if(taxTargetValue == "增值税专用发票" || taxTargetValue == "增值税电子普通发票(交通类)"){
    	        taxAmountTarget.val(parseFloat(newValue));
    	       // noTaxAmountTarget.val(amount - parseFloat(newValue));
    	       // $(noTaxAmountTarget).attr("disabled", true);
    	       // noTaxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	    }
    	}
    });
    
}
//expenses_item 费用种类
function secondCombox(rowIndex){
    var comCode=$('#comCode').combobox('getValue');
    var doctype=$('#doctype').combobox('getValue');
    // var userid=$("#WF_UserName").val();
    var userid=$("#staff_id").val();//凭证
    var row = $('#dg').datagrid('getSelected',rowIndex);
	var target = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'expenses_item'}).target;
}
//二级联动  费用类别  预算项目
function initSecondCombox(data){
    
    var comCode=$('#comCode').combobox('getValue');
    // var userid=$("#WF_UserName").val();
    var userid=$("#staff_id").val();//凭证
    var row = $('#dg').datagrid('getSelected');
    var rowIndex = $('#dg').datagrid('getRowIndex',row);//获取行号
    var targets = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'budget_item'}).target;
    var url = 'rule?wf_num=R_finance_B008&expense='+encodeURIComponent(data)+'&comCode='+comCode+'&userid='+userid;
    targets.combobox({ 
    	url:url,
    	valueField:'id',
    	textField:'text',
    	onLoadSuccess : function() {
	        var  groupdata1 = targets.combobox('getData');
            if (groupdata1 && groupdata1.length==1) {
                 targets.combobox("select",groupdata1[0].text);
                 targets.combobox('disable');
	        }
    	}
    }).combobox({"editable":false});
}

function bulidCostCentre(userid,comCode){
    if(userid == "" || userid== undefined || userid== null){
        userid = $("#staff_id").val();
    }
    if(comCode == "" || comCode== undefined || comCode== null){
        comCode = $('#comCode').combobox('getValue');
    }
    uri = "rule?wf_num=R_finance_B004&userid="+userid+"&comCode="+comCode;
    $('#cost_center').combobox({
      url:uri,
      valueField:'val',
      textField:'text',
      onLoadSuccess:function() {
          groupdata1 = $('#cost_center').combobox('getData');
          if (groupdata1 && groupdata1.length==1) {
              $('#cost_center').combobox("select",groupdata1[0].val);
          }
      }
    });
}



var editFlag = undefined;//设置一个编辑标记，原来的位置
var oldDocType = "";

$(document).ready(function(){
    var comCodeTag = $("#comCode")[0].tagName.toLocaleLowerCase();
    //span标签为只读状态，不加载事件
    if(comCodeTag!="span"){
        //获得登陆用户id
        var userid = $("#staff_id").val();//凭证
        var docID = $("#WF_DocUnid").val();
        var uri = "rule?wf_num=R_finance_B055&userid="+userid +"&docUnid=" + docID;
        //"rule?wf_num=R_finance_B055&userid="+userid;
        $("#comCode").combobox({   
            url:uri,
            valueField:'val', 
            textField:'text',
            onLoadSuccess:function() {
        	    groupdata = $('#comCode').combobox('getData');
        	    //alert("groupdata.length====" + groupdata.length);
        	    if (groupdata && groupdata.length<=2) {
        	        $('#comCode').combobox("select",groupdata[0].val);
        	    } 
        	    //重新选择公司的时候，成本中心不随着改变
        	    bulidCostCentre(userid,$('#comCode').combobox('getValue'));
        	},
        	onSelect:function(rec) {
        	    var doctype = $('#doctype').combobox('getValue');
        	    var aa = $('#comCode').combobox('getValue');
        	    if(aa == "UFDATA_015_2012" || aa == "UFDATA_012_2012" || aa == "UFDATA_019_2013" || aa == "UFDATA_030_2013" || aa == "UFDATA_040_2017"){
        	        alert("测试环境暂无此账套！");
        	        return;
        	    }
        	    var costCentre = $('#cost_center').combobox('getValue');
        	    if(costCentre == ""){
        	        bulidCostCentre(userid,$('#comCode').combobox('getValue'));
        	    }
        	}
        });
        var WF_DocUnid=$("#WF_DocUnid").val(); 
        //判断是否为驳回单据
        var res = 1;
        $.ajax({
            url:'r?wf_num=R_finance_B025&WF_DocUnid='+WF_DocUnid,
            dataType:'json',
            cache:false,
            async:false, 
            success:function(data) {
                res = data;
            }
        });
        //驳回状态
        if(res>0){
            jQuery.ajax({
                type:"post",
                async:false,
                url:"rule?wf_num=R_finance_B023",
                dataType:"text",
                data:{
                    userid:$("#staff_id").val(),
                    docID:WF_DocUnid,
                },
                success:function(data){
                    if (data) {
                        var _data = eval('(' + data + ')');
                        if (_data.length >0) {
                            $('#bene_bank').combobox('setValue',_data[0].text);
                            $('#bank_A_C').combobox('setValue',_data[0].val);
                        }
                    }
                }
            }); 
        }
        if(res<0 && $("#WF_DocStatus").val()!='Draft'){
            jQuery.ajax({
                type:"post",
                async:false,
                url:"rule?wf_num=R_finance_B023",
                dataType:"text",
                data:{
                    userid:$("#staff_id").val(),
                    docID:WF_DocUnid,
                },
                success:function(data){
                    if (data) {
                        var _data = eval('(' + data + ')');
                        if (_data.length >0) {
                            $('#bene_bank').combobox('setValue',_data[0].text);
                            $('#bank_A_C').combobox('setValue',_data[0].val);
                        }
                    }
                }
            }); 
        }
        
        $('#method_payment').combobox({
            url:"rule?wf_num=R_finance_B003",
            valueField:'val',
            textField:'text',
        });
        //报销类型
        var WF_DocUnid=$("#WF_DocUnid").val();
        // $("#payeeFull").attr("readOnly",true);
        // $("#payeeFull").attr('style','background-color: rgb(204, 204, 204);');
        $('#doctype').combobox({
            url:"rule?wf_num=R_finance_B051",
            valueField:'val', 
            textField:'text',
            onLoadSuccess:function() {
        	    groupdata = $('#doctype').combobox('getData');
        	    var nowDocType = $('#doctype').val();
        	    if (groupdata && groupdata.length>0) {
        	        for(var i=0; i<groupdata.length; i++){
        	            if(groupdata[i].val == nowDocType){
        	                $('#doctype').combobox("select",groupdata[i].val);
        	                getReimbTypeList(groupdata[i].val);
        	            }
        	        }
        	        
        	    } 
        	},
            onSelect:function(rec) {//表单类型改变时
                    selDocument();
                    getReimbTypeList(rec.val);
                    if(rec.val == 'staffExpenses'){
                        $("#title").val("业 务 费 用 报 销 单（员工）");//这里赋值的，点击哪个报销类型就加哪个
                     	$("#title1").val("Operating Expenses Reimbursement Form (Staff)");
                     	//默认不可编辑，单据类型为对公预付款申请时才可编辑
                        $("#vendor_code").attr('readonly','readonly');
                        $("#vendor_code").attr('style','background-color: rgb(204, 204, 204);');
                     	document.getElementById('payeeFull').value = $("#staff_name").val();
                     	$("#vendor_code").val("");
                     	var item = $('#dg').datagrid('getRows');
                     	//删除视图中的值
                        if (item) {
                            for (var i = item.length - 1; i >= 0; i--) {
                                var index = $('#dg').datagrid('getRowIndex', item[i]);
                                $('#dg').datagrid('deleteRow', index);
                            }
                        }
                        $("#findVendor").hide();
                 	}
                 	if(rec.val=='supplierExpenses'){
                 	    $("#title").val("业 务 费 用 报 销 单（对公）");
                 	    $("#title1").val("Operating Expenses Reimbursement Form (Supplier)");
                 	    //默认不可编辑，单据类型为对公预付款申请时才可编辑
                        $("#vendor_code").attr('readonly',false);
                        $("#vendor_code").attr('style','');
                        $("#payeeFull").val("");
                     	$("#vendor_code").val("");
                 	    $('#controlDiv').show();
                 	    $("#findVendor").show();
                 	}
            }
        });
        ///////////////////
        $('#findGR').hide();
        $('#ifLinkGR').combobox({
                //表单类型改变时
                onSelect:function(rec) {
                    
                    if(rec.val == 'linkGR'){
                        $('#findGR').show();
                 	}else{
                 	    $('#findGR').hide();
                 	}
                }
            });
        //////////////////
    }  
});

//1.模糊查询客户名称
function getVendorName(val){
    //alert("模糊查询供应商名称" + val);
    var b;
    var doctype = $("#doctype").combobox("getValue");
    if(doctype == null || doctype == ""){
        alert("请先选择单据类型！");
        return false;
    }
    //var comCode = $('#comCode').children('option:selected').val();//这就是selected的值
    var comCode = $('#comCode').combobox('getValue');
    if(comCode == ''){
        alert("请先选择费用所属公司！");
        return;
    }
  var payeeFull = $("#payeeFull").val();
  //alert("======" + payeeFull);
  //var DepartmentID= $("#DepartmentID").val();
  //模糊匹配客户名称
  jQuery.ajax({
      type:"post",
      async:false,
      url:"rule?wf_num=R_finance_B070",
      dataType:"text",
      data:{
            payeeFull:payeeFull,
            comCode:comCode
      },
      success:function(data){
          checkword(data);
      }
  });
}
//2.扩展模糊查询出来的序列值
function checkword(val){
    var wordvalue=document.getElementById("payeeFull").value.toLowerCase();
    var alltxt=val;
    //var inhtml="<ul>";
    var inhtml="<table border='2'\" width ='300px'>";
    var isyou=0;
    var alltxtName = alltxt.split(",");
    for(i=0;i<alltxtName.length;i++){
        //alert("=======" + alltxtName[i]);
        var alltxtNameNext = alltxtName[i].split("|");
        //alert("******" + alltxtNameNext[1]);
        var name = alltxtNameNext[0];
        var value = alltxtNameNext[1];
        inhtml=inhtml+"<tr><td onclick=\"fz(this.innerHTML)\" onmouseover=\"this.style.backgroundColor='#666666'\" onmouseout=\"this.style.backgroundColor=''\" style=\"font-weight:bold\">"
        +name +"<p style=\"display:none\">"+value+"</p>"+"<td/></tr>";
        isyou=1;
    }
    inhtml=inhtml+"</table>";
    //alert("******" + inhtml);
    if (isyou==1){
        //alert("123456");
      document.getElementById("showmenu").innerHTML=inhtml;
      document.getElementById("showmenu").style.display="";
    }else{
      document.getElementById("showmenu").innerHTML="";
      document.getElementById("showmenu").style.display="none";
    }
    if (wordvalue==""){
      document.getElementById("showmenu").innerHTML="";
      document.getElementById("showmenu").style.display="none";
    }
}
//3.给相关联的字段赋值
function fz(val){
    var b = val.split("<");
    //alert("******" + b);
    var c = b[1].split(">");
    var a;
    //客户名称赋值
    $("#payeeFull").val(b[0]);
    //$("#payeeFull").attr('readonly','readonly');
    //$("#payeeFull").attr('style','background-color: rgb(204, 204, 204);');
    document.getElementById("showmenu").style.display="none";
    $("#payeeFullCode").val(c[1]);//供应商编号

    $("#vendor_code").val(c[1]);
    $("#vendor_code").attr('readonly','readonly');
    $("#vendor_code").attr('style','background-color: rgb(204, 204, 204);');
    //支付方式 method_payment
    $('#method_payment').combobox({
        url:"rule?wf_num=R_finance_B003",
        valueField:'val',
        textField:'text',
    }).combobox({"editable":false}).combobox({disabled:true});
	$("#bank_A_C").combobox({
	    //银行卡号
        url:"rule?wf_num=R_finance_B023&type=vendor&vendorCode=" + c[1],
        valueField:'val', 
        textField:'text'
	}).combobox({"editable":false}).combobox({disabled:true});
	//开户行
    $('#bene_bank').combobox({
        url:"rule?wf_num=R_finance_B033&type=vendor&vendorCode=" + c[1],
        valueField:'val',
        textField:'text',
        
    }).combobox({"editable":false}).combobox({disabled:true});
    
    
}

//增加解除锁定表
var flag = true;
window.onbeforeunload = function () {
    if (flag) {
        var evt = window.event || arguments[0];
        var userAgent = navigator.userAgent;
        if (userAgent.indexOf("Firefox") > 0) {
            $.ajax({
                url:'r?wf_num=R_finance_B030&WF_DocUnid='+$("#WF_DocUnid").val(),
                type:'post',
                dataType:'json',
                contentType: "application/json; charset=utf-8",
                async:false, 
                success:function(data) {

                }
            });
        }
    }
}